import {App} from "vue";

interface Options{
    url: string;
}
class WebSocketPlugin {
    public url: string;
    public ws: WebSocket | null = null;
    
    constructor(url: string) {
        this.url = url;
        this.ws = new WebSocket(url)
        
    }
    onopen(cb: Function): any {
        if(this.ws) {
            this.ws.onopen = (event:Event) => {
                console.log("WebSocket 已连接！" + event)
                cb()
            }
        }
    }
    
    onmessage(cb:Function):any{
        if(this.ws) {
            this.ws.onmessage = (event:Event) => {
                console.log("WebSocket 接收到消息！" + event)
                cb()
            }
        }
    }
    
    onerror(cb: Function): any{
        if(this.ws) {
            this.ws.onerror = (event:Event) => {
                console.log("WebSocket 发生错误："+event)
                console.log(event)
                cb()
            }
        }
    }
    
    onclose(cb: Function){
        if(this.ws) {
            this.ws.onclose = (event:Event) => {
                console.log("WebSocket已关闭！"+event)
                cb()
            }
        }
    }
    
    send(object: Object):void{
        if(this.ws){
           this.ws.send(JSON.stringify(object)) 
        }
        
    }
    
    
    
}

export default {
    install(app: App, options: Options) {
        const wsPlugin = new WebSocketPlugin(options.url)
        //注入ws
        app.provide('wsPlugin', wsPlugin)
    }
}